package com.emm.yixun.customer.service.impl;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.CustTagService;
import com.emm.yixun.basic.service.CustomerAnswerService;
import com.emm.yixun.basic.service.CustomerProjectAnswerService;
import com.emm.yixun.basic.service.MerchantService;
import com.emm.yixun.basic.service.TagValueService;
import com.emm.yixun.common.app.CustomerTagListReqDto;
import com.emm.yixun.common.app.CustomerTagListResDto;
import com.emm.yixun.common.app.servletentity.CustTaglistRes;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.CustTag;
import com.emm.yixun.common.model.CustTagInfo;
import com.emm.yixun.common.model.CustomerAnswer;
import com.emm.yixun.common.model.CustomerProjectAnswer;
import com.emm.yixun.common.model.Merchant;
import com.emm.yixun.common.model.TagValue;
import com.emm.yixun.common.model.dto.CustTagDto;
import com.emm.yixun.common.model.dto.CustomerAnswerDto;
import com.emm.yixun.common.model.dto.MerchantDto;
import com.emm.yixun.common.model.dto.TagValueDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.config.DsfConfig;
import com.emm.yixun.customer.service.CustTagServiceFacade;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("custTagServiceFacade")
@WebService(name = "com.emm.yixun.customer.service.CustTagServiceFacade")
public class CustTagServiceFacadeImpl implements CustTagServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CustTagService service;

	@Autowired
	private TagValueService tagValueService;

	@Autowired
	private MerchantService merchantService;

	@Autowired
	private CustomerProjectAnswerService customerProjectAnswerService;

	@Autowired
	private CustomerAnswerService customerAnswerService;

	@Override
	public Response<CustTagDto> save(CustTagDto dto) {
		Response<CustTagDto> response = new Response<CustTagDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			CustTagDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(CustTagDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			CustTagDto mDto = new CustTagDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<CustTag> findById(Long id) {
		Response<CustTag> response = new Response<CustTag>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			CustTag entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<CustTag> findByDto(CustTagDto dto) {
		ResponseList<CustTag> response = new ResponseList<CustTag>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<CustTag> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<CustTagInfo> findPageByDto(CustTagDto dto, Integer begin, Integer row) {
		Page<CustTagInfo> response = new Page<CustTagInfo>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<CustTagInfo> page = service.getCusTagPage(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<CustTagDto> saveCusTag(CustTagDto dto, String jsonArray) {
		Response<CustTagDto> response = new Response<CustTagDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			CustTagDto mDto = null;
			JSONArray array = JSONArray.fromObject(jsonArray);
			for (int i = 0; i < array.size(); i++) {
				JSONObject json = (JSONObject) array.get(i);
				dto.setTagExtId(json.getLong("questionId"));
				dto.setTagId(json.getLong("tagId"));
				if ("3".equals(json.getString("answerType"))) {
					// 当答案为文本时，直接保存
					dto.setTagValueId(null);
					dto.setTagValue(json.getString("answerText"));
					// 修改问卷答案
					updateCustomerAnswer(dto, 0);
				} else {
					// 当答案为选项时，先查询出答案value，在保存
					String answerId = json.getString("answerId");
					answerId = answerId.replace("[\"", "").replace("\"]", "").replace("\",\"", ",");
					String answer = getTagValue(dto.getTagId(), answerId);
					dto.setTagValueId(answerId);
					dto.setTagValue(answer);
					// 修改问卷答案
					updateCustomerAnswer(dto, 0);
				}
				dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				mDto = service.create(dto);
			}

			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	/**
	 * 获取答案
	 * 
	 * @param tagId
	 * @param answerId
	 * @return
	 */
	private String getTagValue(Long tagId, String answerId) {
		TagValueDto entity = new TagValueDto();
		entity.setIds(answerId);
		entity.setTagId(tagId);
		List<TagValue> list = tagValueService.selectListByIds(entity);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			TagValue tag = (TagValue) list.get(i);
			sb.append(tag.getTValue());
			if (i < (list.size() - 1)) {
				sb.append(",");
			}
		}
		return sb.toString();
	}

	@Override
	public Response<Integer> editCusTag(CustTagDto dto, String jsonArray) {
		Response<Integer> response = new Response<Integer>();
		try {
			JSONArray array = JSONArray.fromObject(jsonArray);
			for (int i = 0; i < array.size(); i++) {
				JSONObject json = (JSONObject) array.get(i);
				if ("3".equals(json.getString("answerType"))) {
					// 当答案为文本时，直接保存
					dto.setTagValueId(null);
					dto.setTagValue(json.getString("answerText"));
					// 修改问卷答案
					updateCustomerAnswer(dto, 1);
				} else {
					// 当答案为选项时，先查询出答案value，在保存
					String answerId = json.getString("answerId");
					answerId = answerId.replace("[\"", "").replace("\"]", "").replace("\",\"", ",");
					String answer = getTagValue(dto.getTagId(), answerId);
					dto.setTagValueId(answerId);
					dto.setTagValue(answer);
					// 修改问卷答案
					updateCustomerAnswer(dto, 1);
				}
			}

			int count = service.update(dto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "更新数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	/**
	 * 修改问卷答案
	 * 
	 * @param dto
	 * @param flag
	 *            0 新增标签答案时，先查询对应答案ID 1 修改标签答案时，先查询对应标签ID，再获取对应答案ID
	 * @return
	 */
	private String updateCustomerAnswer(CustTagDto dto, int flag) {
		// 修改标签答案时，先查询对应标签ID
		if (flag == 1) {
			CustTag ct = service.selectById(dto.getId());
			dto.setCustomerId(ct.getCustomerId());
			dto.setTagExtId(ct.getTagExtId());
		}
		// 查询是否已填写问卷答案
		CustomerAnswer ca = customerAnswerService.getCusAnswerIdByTag(dto.getCustomerId(), dto.getTagExtId());
		// 未查询到已填写的问卷答案，退出后续操作
		if (ca == null) {
			return null;
		}
		// 当答案表不为空时，逻辑删除已填写的问卷答案
		if (StringUtils.isNotBlank(ca.getAnswerValue())) {
			customerAnswerService.destroys(ca.getAnswerValue());
		}

		// 保存新答案
		CustomerAnswerDto entity = new CustomerAnswerDto();
		entity.setCustomerId(dto.getCustomerId());
		entity.setProjectQuestionnaireId(ca.getProjectQuestionnaireId());
		entity.setCustomerProjectQuestionId(ca.getCustomerProjectQuestionId());
		entity.setAnswerType(ca.getAnswerType());
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		// 当答案类型为选项时，查询对应问卷答案中的答案ID，并保存到客户答案表，否则，直接进行保存
		if ("1".equals(ca.getAnswerType()) || "2".equals(ca.getAnswerType())) {
			saveCustomerAnswer(dto, entity);
		} else {
			entity.setAnswerValue(dto.getTagValue());
			customerAnswerService.create(entity);
		}
		return null;
	}

	/**
	 * 保存选项答案
	 * 
	 * @param dto
	 * @param entity
	 * @return
	 */
	private void saveCustomerAnswer(CustTagDto dto, CustomerAnswerDto entity) {
		// 查询对应问卷答案中的答案ID
		StringBuffer answerArray = new StringBuffer();
		answerArray.append("'");
		answerArray.append(dto.getTagValue().replaceAll(",", "','"));
		answerArray.append("'");
		List<CustomerProjectAnswer> list = customerProjectAnswerService.getAnswerByTag(dto.getCustomerId(),
				dto.getTagExtId(), answerArray.toString());
		// 循环保存
		for (CustomerProjectAnswer answer : list) {
			entity.setCustomerProjectAnswerId(answer.getId());
			customerAnswerService.create(entity);
		}
	}

	@Override
	public Page<CustTagInfo> getCusTagInfoPage(CustTagDto dto, Integer begin, Integer row) {
		Page<CustTagInfo> response = new Page<CustTagInfo>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<CustTagInfo> page = service.getCusTagInfoPage(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	/**
	 * “回来了社区” 客户标签信息全量查询接口
	 */
	@Override
	public CustomerTagListResDto getCusTagListPage(CustomerTagListReqDto reqDto) {
		CustomerTagListResDto resDto = new CustomerTagListResDto();

		// 验证接口参数准确性
		boolean flag = DsfConfig.validSign(reqDto);
		if (!flag) {
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		// 验证分页参数时候正确
		Integer pageNum = reqDto.getPageNum();
		Integer pageSize = reqDto.getPageSize();
		if (null == pageNum || null == pageSize) {
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("pageNum或pageSize为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		// 验证查询条件时候正确
		String starTime = reqDto.getStarTime(); // 开始时间
		String endTime = reqDto.getEndTime(); // 结束时间
		if (StringUtils.isBlank(starTime) || StringUtils.isBlank(endTime)) {
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("starTime或endTime为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		if (starTime.length() == 10) {
			starTime = starTime + " 00:00:00";
		}
		if (endTime.length() == 10) {
			endTime = endTime + " 23:59:59";
		}

		try {
			// 验证授权码是否正确
			MerchantDto merDto = new MerchantDto();
			merDto.setMerchantCode(reqDto.getToken());
			merDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			Merchant merchant = merchantService.selectByDto(merDto);
			if (merchant == null) {
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("授权码验证失败！");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}

			// 查询数据主体
			SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

			CustTagDto entity = new CustTagDto();
			entity.setMerchantId(merchant.getId());
			entity.setUpdateTimeBefore(sft.parse(starTime));
			entity.setUpdateTimeAfter(sft.parse(endTime));
			Page<CustTaglistRes> page = service.getCustomerTagPage(entity, PageUtil.begin(pageNum, pageSize), pageSize);
			// 组装返回res
			if (page == null) {
				resDto.setErrorCode("99999");
				resDto.setErrorMsg("客户标签信息全量接口查询失败");
				resDto.setResult(ResultEnum.FAILURE.getNo());
			}
			List<CustTaglistRes> customerTagList = page.getRows();
			resDto.setCustomerTagList(customerTagList);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setTotalPageNum(page.getTotalPages());

		} catch (Exception e) {
			resDto.setErrorCode("99999");
			resDto.setErrorMsg("客户标签信息全量接口查询失败");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			logger.error("客户标签信息全量接口查询失败,{}", e);
		}
		return resDto;
	}

	/**
	 * “回来了社区” 客户问卷全量查询接口
	 */
	@Override
	public CustomerTagListResDto getCustomerQuestionnairePage(CustomerTagListReqDto reqDto) {
		CustomerTagListResDto resDto = new CustomerTagListResDto();

		// 验证接口参数准确性
		boolean flag = DsfConfig.validSign(reqDto);
		if (!flag) {
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		// 验证分页参数时候正确
		Integer pageNum = reqDto.getPageNum();
		Integer pageSize = reqDto.getPageSize();
		if (null == pageNum || null == pageSize) {
			// resDto.setErrorCode("00000");
			// resDto.setErrorMsg("pageNum或pageSize为空");
			// resDto.setResult(ResultEnum.FAILURE.getNo());
			// return resDto;
			// 默认设置
			pageNum = 1;
			pageSize = 100;
		}
		// 验证查询条件时候正确
		String starTime = reqDto.getStarTime(); // 开始时间
		String endTime = reqDto.getEndTime(); // 结束时间
		if (StringUtils.isBlank(starTime) || StringUtils.isBlank(endTime)) {
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("starTime或endTime为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		if (starTime.length() == 10) {
			starTime = starTime + " 00:00:00";
		}
		if (endTime.length() == 10) {
			endTime = endTime + " 23:59:59";
		}

		try {
			// 验证授权码是否正确
			MerchantDto merDto = new MerchantDto();
			merDto.setMerchantCode(reqDto.getToken());
			merDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			Merchant merchant = merchantService.selectByDto(merDto);
			if (merchant == null) {
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("授权码验证失败！");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}

			SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			// 查询数据主体
			CustTagDto entity = new CustTagDto();
			entity.setMerchantId(merchant.getId());
			entity.setUpdateTimeBefore(sft.parse(starTime));
			entity.setUpdateTimeAfter(sft.parse(endTime));
			Page<CustTaglistRes> page = service.customerQuestionnairePage(entity, reqDto.getProjectCode(),
					PageUtil.begin(pageNum, pageSize), pageSize);
			// 组装返回res
			if (page == null) {
				resDto.setErrorCode("99999");
				resDto.setErrorMsg("客户标签信息全量接口查询失败");
				resDto.setResult(ResultEnum.FAILURE.getNo());
			}
			List<CustTaglistRes> customerTagList = page.getRows();
			resDto.setCustomerTagList(customerTagList);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setTotalPageNum(page.getTotalPages());

		} catch (Exception e) {
			resDto.setErrorCode("99999");
			resDto.setErrorMsg("客户标签信息全量接口查询失败");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			logger.error("客户标签信息全量接口查询失败,{}", e);
		}
		return resDto;
	}

	@Override
	public Response<CustTagDto> saveOrEditCusTag(CustTagDto dto, String jsonArray, String ids, String type) {
		Response<CustTagDto> response = new Response<CustTagDto>();
		if (StringUtils.isNotBlank(ids)) {
			// 已有标签答案时进行修改操作
			dto.setId(Long.parseLong(ids));
			Response<Integer> res = editCusTag(dto, jsonArray);
			if (res.isSuccess()) {
				response.setSuccess(true);
			} else {
				response.setSuccess(false);
			}
		} else {
			// 保存标签答案
			response = saveCusTag(dto, jsonArray);
		}

		return response;
	}

	public List<CustTaglistRes> getCustomerAnswerList(Long projectId, Long questionnaireId) {
		List<CustTaglistRes> list = service.getCustomerAnswerList(projectId, questionnaireId);
		return list;
	}
}